import http from '../../../utils/https.js';

Page({
  data: {
    currentTab: 0, // 当前选中的tab索引
    announcements: [], // 从后端获取的数据
    filteredList: [] // 过滤后的列表
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.getAnnouncementList();
  },

  /**
   * 获取公告列表
   */
  getAnnouncementList: function() {
    wx.showLoading({ title: '加载中...' });
    
    http.get('property/notice/list')
      .then(res => {
        if (res.code === 200) {
          // 按发布日期降序排序
          const sortedList = res.rows.sort((a, b) => 
            new Date(b.publishTime) - new Date(a.publishTime)
          );
          
          // 映射字段并添加已读状态
          const announcements = sortedList.map(item => {
            // 从本地存储获取已读状态
            const isRead = wx.getStorageSync(`notice_${item.id}`) || false;
            
            // 紧急程度映射
            let tag = '';
            switch (item.noticeLevel) {
              case 1: tag = '一般'; break;
              case 2: tag = '紧急'; break;
              case 3: tag = '非常紧急'; break;
              default: tag = '通知';
            }
            
            return {
              id: item.id,
              title: item.noticeTitle,
              content: item.noticeDetail,
              isRead: isRead,
              date: this.formatDate(item.publishTime),
              tag: tag,
              source: item.organizer, // 举办方作为来源
              type: 'announcement'
            };
          });
          
          this.setData({ announcements }, () => {
            this.filterAnnouncements();
            wx.hideLoading();
          });
        }
      })
      .catch(err => {
        console.error('获取公告失败:', err);
        wx.hideLoading();
        wx.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
      });
  },

  /**
   * 格式化日期
   */
  formatDate: function(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}/${month}/${day}`;
  },

  /**
   * 切换Tab
   */
  switchTab: function(e) {
    const index = parseInt(e.currentTarget.dataset.index);
    this.setData({ currentTab: index }, () => {
      this.filterAnnouncements();
    });
  },

  /**
   * 过滤公告数据
   */
  filterAnnouncements: function() {
    const { currentTab, announcements } = this.data;
    let filteredList = [];
    
    if (currentTab === 0) {
      filteredList = announcements;
    } else if (currentTab === 1) {
      filteredList = announcements.filter(item => !item.isRead);
    } else if (currentTab === 2) {
      filteredList = announcements.filter(item => item.isRead);
    }
    
    this.setData({ filteredList });
  },

  /**
   * 永久标记为已读
   */
  markAsRead: function(id) {
    // 更新本地存储
    wx.setStorageSync(`notice_${id}`, true);
    
    // 更新数据状态
    const announcements = this.data.announcements.map(item => {
      if (item.id === id) {
        return {...item, isRead: true};
      }
      return item;
    });
    
    this.setData({ announcements }, () => {
      this.filterAnnouncements();
    });
  },

  /**
   * 处理公告点击事件
   */
  handleAnnouncementTap: function(e) {
    const id = e.currentTarget.dataset.id;
    
    // 标记为已读
    this.markAsRead(id);
    
    // 导航到详情页
    wx.navigateTo({
      url: `/service/pages/announcementDetails/announcementDetails?id=${id}`
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.filterAnnouncements();
  },

  /**
   * 返回上一页
   */
  goBack: function() {
    wx.navigateBack();
  }
});